package integracion;

import dominio.Accion;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import persistencia.*;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author DaKaLu
 */
public class ControlAccion
{
    private static List<Accion> accionesPorEnviar = null;
    private static PersistenciaXML persistencia = new ManejoXml();

    public static void leer() {
        accionesPorEnviar = persistencia.leerAcciones();
    }

    public static void escribir() {
        if (accionesPorEnviar != null) {
            persistencia.escribirAcciones(accionesPorEnviar);
        } else {
            System.out.println("No se puede persistir una lista vacia");
        }
    }

     public static void agregar(Accion miAccion) {
        accionesPorEnviar.add(miAccion);
    }

    public static void crearAccion() {
        accionesPorEnviar = new ArrayList<Accion>();
        accionesPorEnviar.add(new Accion("cancion_1", "artista_1", "url_1.au","aa","aa","3"));
    }

    public synchronized void escribirAccion(byte[] result)
    {
        try
        {
            FileOutputStream out = new FileOutputStream("archivos/XML/Acciones.xml");
            out.write(result);
            out.close();
        } catch (Exception e) {
           System.out.println("Error de escritura, archivo de errores");
        }
    }

    public synchronized byte[] modificarString(String result)
    {
        String aux;
        //result = result.replaceAll("<StockQuotes>","<StockQuotes xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:ns0='http://xml.netbeans.org/schema/AccionesXmlSchema' xsi:schemaLocation='http://xml.netbeans.org/schema/AccionesXmlSchema AccionesXmlSchema.xsd'>");
        //result = result.replaceAll("<","<ns0:");
        //result = result.replaceAll("<ns0:/","</ns0:");
        aux = result.substring(0,result.indexOf("<Change>"));
        aux = result + result.substring(result.indexOf("<Name>"),result.length());
        aux = "<?xml version="+"1.0"+" encoding="+"UTF-8"+"?>"+aux;
        return (aux.getBytes());
    }

    public synchronized void traerAccion(String accion)
    {
        String result = null;
        try
        {
            net.webservicex.StockQuote service = new net.webservicex.StockQuote();
            net.webservicex.StockQuoteSoap port = service.getStockQuoteSoap();
            result = port.getQuote(accion);
            escribirAccion(modificarString(result));
        } catch (Exception ex) {
            System.out.println("ERROR: "+ex);
        }
    }

}
